#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//#include <malloc.h>
#include "CString.h"

CString *Init_CString(char *str)
{
	CString *p = NULL;

	if (str == NULL){
		return NULL;
	}
	
	p = (CString *)malloc(sizeof(CString));
	if (p == NULL){
		perror("CString malloc");
		return NULL;
	}
	p->str = NULL;

	p->length = strlen(str);
	p->str = (char *)malloc(p->length + 1);
	if (p->str == NULL){
		perror("p->str malloc");
		free(p);
		return NULL;
	}

	// copy the str to p->str.
	strcpy(p->str,str);

	return p;
}

void Delete_CString(CString *p)
{
	if (p == NULL){
		return;
	}
	free(p->str);
	free(p);
	p = NULL;
}

char *Get_string(CString *p)
{
	if (p == NULL){
		return NULL;
	}

	return p->str;
}

int Length(CString *p)
{
	if (p == NULL){
		return 0;
	}

	return p->length;
}

//remove the last character of CString and return it.
char Chomp(CString *cstring)
{
	char ch;

	if (cstring == NULL){
		return '\0';
	}

	if (cstring->length == 0){
		return '\0';
	}

	ch = cstring->str[cstring->length - 1];
	cstring->str[cstring->length - 1] = '\0';
	cstring->length -= 1;

	return ch;

}

//Appends a string to a CString.
CString *Append_Chars_To_CString(CString *p,char *str)
{
	char *newbase = NULL;

	if (p == NULL || str == NULL){
		return p;
	}

	p->length = p->length + strlen(str);

	newbase =(char *)realloc(p->str,p->length + 1);
	if (newbase == NULL){
		perror("newbase realloc");
		return p;
	}

	p->str = newbase;
	strcat(p->str,str);

	return p;
}



